package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义权限不足处理类
 */
@Service
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 处理权限不足的异常
     * @param request   请求对象
     * @param response  响应对象
     * @param accessDeniedException  权限不足时的异常对象
     * @throws IOException   处理过程中可能出现IO异常
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.debug("权限不足");
        //设置响应的状态码为403，表示权限不足禁止访问
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //设置响应内容类型和编码集
        response.setContentType("application/json;charset=UTF-8");
        //响应内容
        PrintWriter writer = response.getWriter();
        //准备一个用于响应内容的JSON对象
        JsonResult jsonResult = new JsonResult(StatusCode.NOT_LOGIN);
        writer.write(JSON.toJSONString(jsonResult));
        //刷新并关闭
        writer.flush();
        writer.close();
    }
}
